<template>
  <view class="box">
    <uv-navbar 
      class="bold-title" 
      title="发情记录" 
      @leftClick="leftClick"
      :safeAreaInsetTop="true"
      :placeholder="true"
      :height="'44px'"
    ></uv-navbar>
    
    <view class="content-area">
      <InfoTitleList :infoTitleList="animalInfoList0"></InfoTitleList>
      <view class="form-item">
        <text class="label">牧民</text>
        <input v-model="formData.F_Opert" placeholder="韩梅梅" class="input" />
      </view>
      <view class="form-item">
        <text class="label">电话</text>
        <input v-model="formData.F_Phone" placeholder="未填写" class="input" />
      </view>
      <view class="form-item">
        <text class="label">地址</text>
        <input v-model="formData.F_Address" placeholder="未选择" class="input" />
      </view>
      <InfoTitleList :infoTitleList="animalInfoList1"></InfoTitleList>
      <view class="form-item">
        <text class="label">选择牲畜</text>
        <CattleDropdown 
          :cattleList="cattleList" 
          @select="handleCattleSelect" 
          :placeholder="'IMEI 12345678911'"
        />
      </view>
      <view class="form-item">
        <text class="label">实际发情时间</text>
        <picker 
          mode="date" 
          :value="formData.F_SjTimateTime" 
          start="2020-01-01" 
          end="2030-12-31" 
          @change="handleSjTimeChange"
        >
          <view class="picker">
            {{ formData.F_SjTimateTime || '未选择' }}
          </view>
        </picker>
      </view>
      <view class="form-item">
        <text class="label">预测发情时间</text>
        <picker 
          mode="date" 
          :value="formData.F_EsTimateTime" 
          start="2020-01-01" 
          end="2030-12-31" 
          @change="handleEsTimeChange"
        >
          <view class="picker">
            {{ formData.F_EsTimateTime || '未选择' }}
          </view>
        </picker>
      </view>
      <view class="form-item no-border">
        <text class="label">备注</text>
        <textarea v-model="formData.F_Remark" placeholder="" class="input"></textarea>
      </view>
    </view>
    
    <view class="header">
      <button class="add-button" @click="submitForm">提交</button>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import InfoTitleList from '@/components/Animals/InfoTitleList.vue';
import CattleDropdown from '@/components/Quarantinehome/CattleDropdown.vue';
import { addBreeding } from '@/api/manageLeft.js';
import { getCattleList } from '@/api/manageRight.js';

const formData = ref({
  F_liveid: '',
  F_EsTimateTime: '',
  F_SjTimateTime: '',
  F_Opert: '',
  F_Phone: '',
  F_Address: '',
  F_Remark: ''
});

const isLoading = ref(false); // 加载状态

const animalInfoList0 = ref([{ title: '牧民信息（操作员）' }]);
const animalInfoList1 = ref([{ title: '添加牲畜' }]);

const cattleList = ref([]);
// 加载牲畜列表
const loadCattleList = async () => {
  try {
    const response = await getCattleList();
    if (response.code === 200 && response.data) {
      cattleList.value = response.data.map(item => ({
        id: item.F_Id,
        imei: item.F_IMEI
      }));
    } else {
      uni.showToast({ title: '获取牲畜列表失败', icon: 'none' });
    }
  } catch (error) {
    console.error('获取牲畜列表错误:', error);
    uni.showToast({ title: '网络错误，请重试', icon: 'none' });
  }
};

// 选择牲畜处理
const handleCattleSelect = (selectedCattle) => {
  if (selectedCattle) {
    formData.value.F_liveid = selectedCattle; // 只取id属性
    console.log('选中的牲畜ID:', formData.value.F_liveid); // 调试输出
  } else {
    uni.showToast({ title: '请选择有效牲畜', icon: 'none' });
  }
};

// 实际发情时间变更
const handleSjTimeChange = (e) => {
  formData.value.F_SjTimateTime = e.detail.value;
};

// 预测发情时间变更
const handleEsTimeChange = (e) => {
  formData.value.F_EsTimateTime = e.detail.value;
};

// 提交表单
const submitForm = async () => {
  // 校验必填字段
  const requiredFields = [
    'F_liveid', 'F_EsTimateTime', 'F_SjTimateTime',
    'F_Opert', 'F_Phone', 'F_Address', 'F_Remark'
  ];
  
  const missingFields = requiredFields.filter(
    field => !formData.value[field]
  );
  
  if (missingFields.length > 0) {
    return uni.showToast({
      title: `请填写必填项：${missingFields.join('、')}`,
      icon: 'none'
    });
  }

  try {
    const response = await addBreeding(formData.value);
    if (response.code === 200) {
    
	  console.log(response.msg);
	   uni.navigateBack();
      // 重置表单
      formData.value = {
        F_liveid: '',
        F_EsTimateTime: '',
        F_SjTimateTime: '',
        F_Opert: '',
        F_Phone: '',
        F_Address: '',
        F_Remark: ''
      };
    } else {
      uni.showToast({
        title: response.msg || '添加失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('提交失败:', error);
    uni.showToast({
      title: '网络错误，请重试',
      icon: 'none'
    });
  }
};

// 返回按钮
const leftClick = () => {
  uni.navigateBack();
};

// 组件挂载时加载数据
onMounted(() => {
  loadCattleList();
});
</script>

<style lang="scss" scoped>
.box {
  display: flex;
  flex-direction: column;
  height: 100vh;
}

.bold-title {
  font-weight: 500;
}

.content-area {
  flex: 1;
  overflow: auto;
}

.form-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10rpx 0;
  border-bottom: 2rpx solid #eee;
}

.form-item.no-border {
  display: flex;
  align-items: flex-start;
  padding: 10rpx 0;
  border-bottom: none;
  
  .label {
    width: auto;
    margin-left: 3%;
    padding-right: 20rpx;
    flex-shrink: 0;
    padding-top: 20rpx;
  }

  .textarea {
    flex: 1;
    margin-right: 3%;
    min-height: 100rpx;
    text-align: right;
    border: 1rpx solid #eee;
    box-sizing: border-box;
  }
}

.label {
  font-size: 24rpx;
  color: #333;
  margin-left: 3%; 
  width: 30%;
  padding-right: 20rpx;
}

.input, .textarea, .picker {
  font-size: 24rpx;
  color: #666;
  flex:1;
  background-color: #fff;
  border-radius: 8rpx;
  padding: 20rpx;
  outline: none;
  text-align: right;
}

.header {
  .add-button {
    background-color: #0bcb75;
    color: white;
    border: none;
    border-radius: 8rpx;
    padding: 16rpx;
    width: 100%;
    font-size: 32rpx;
    margin-top: 40rpx;
    position: fixed;
    bottom: 0;
    left: 0;
  }
}
</style>